package com.shiwaixiangcun.customer.module.property

import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.TextView
import com.google.gson.reflect.TypeToken
import com.lzy.okgo.model.HttpParams
import com.shiwaixiangcun.customer.GlobalApi
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.base.BaseActivity
import com.shiwaixiangcun.customer.entity.CommonDataList
import com.shiwaixiangcun.customer.entity.MyPropertyEntity
import com.shiwaixiangcun.customer.event.EventUtil
import com.shiwaixiangcun.customer.event.SimpleEvent
import com.shiwaixiangcun.customer.network.NetworkHelper
import com.shiwaixiangcun.customer.ui.activity.ResidentCertificationActivity
import com.shiwaixiangcun.customer.ui.dialog.PopupWidowDialog
import com.shiwaixiangcun.customer.utils.JsonUtil
import kotlinx.android.synthetic.main.activity_property_payment.*
import kotlinx.android.synthetic.main.top_bar_blue.*
import me.bakumon.statuslayoutmanager.library.OnStatusChildClickListener
import me.bakumon.statuslayoutmanager.library.StatusLayoutManager
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * 物业缴费
 */
class PropertyPaymentActivity : BaseActivity(), View.OnClickListener {

    private var mNetworkHelper: NetworkHelper? = null
    private var statusLayoutManager: StatusLayoutManager? = null
    private var mMultiPaymentFragment: MultiPaymentFragment? = null
    private var finishImmediately = false
    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.back_left -> {

                handleBackKey()
            }
            R.id.iv_share_right -> {

                val popupWidowDialog = PopupWidowDialog()
                popupWidowDialog.show(fragmentManager, "popupWindow")
            }

        }
    }

    /**
     * 处理返回
     */
    private fun handleBackKey() {
        if (finishImmediately) {
            finish()
        } else {
            val backStackEntryCount = supportFragmentManager.backStackEntryCount
            if (backStackEntryCount > 0) {
                val fragments = supportFragmentManager.fragments
                supportFragmentManager.popBackStack()
            } else {
                finish()
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_property_payment)
        EventUtil.getInstance().register(this)
        initEmptyView()
        initViewAndEvent()
        initData()

    }

//    override fun onRestart() {
//        super.onRestart()
//        initData()
//    }

    private fun initEmptyView() {
        val emptyView = LayoutInflater.from(mContext).inflate(R.layout.empty_no_property, null, false)
        emptyView.findViewById<TextView>(R.id.tv_empty).text = "你还没有添加房产"
        emptyView.findViewById<Button>(R.id.btn_add_property).setOnClickListener {
            val bundle = Bundle()
            bundle.putString("type", "add")
            readyGo(ResidentCertificationActivity::class.java, bundle)
        }
        statusLayoutManager = StatusLayoutManager.Builder(property_content)
                .setDefaultLayoutsBackgroundColor(Color.WHITE)
                .setEmptyLayout(emptyView)
                .setErrorLayout(R.layout.layout_error)
                .setOnStatusChildClickListener(object : OnStatusChildClickListener {
                    override fun onErrorChildClick(p0: View?) {
                        initData()
                    }

                    override fun onEmptyChildClick(p0: View?) {
                    }

                    override fun onCustomerChildClick(p0: View?) {
                    }
                })
                .build()
    }

    private fun initData() {
        mNetworkHelper = NetworkHelper(this, supportFragmentManager)
        val httpParams = HttpParams()

        mNetworkHelper?.getRequestWithToken(GlobalApi.getPropertyList, true, httpParams, object : NetworkHelper.NetWorkHelperBack {
            override fun requestSuccess(json: String) {
                val type = object : TypeToken<CommonDataList<MyPropertyEntity>>() {}.type
                val fromJson = JsonUtil.fromJson<CommonDataList<MyPropertyEntity>>(json, type)
                when {
                    fromJson == null -> showToastShort("获取失败")
                    fromJson.success -> when (fromJson.responseCode) {
                        1001 -> {
                            if (fromJson.data.isEmpty()) {

                                val bundle = Bundle()
                                bundle.putInt("fromActivity", 0x0001)
                                bundle.putString("type", "add")
                                readyGo(ResidentCertificationActivity::class.java, bundle)

                            } else {
                                statusLayoutManager?.showSuccessLayout()
                                //当存在多套房产的时候进入列表
                                if (fromJson.data.size > 1) {

                                    mMultiPaymentFragment = MultiPaymentFragment.newInstance(json)
                                    supportFragmentManager
                                            .beginTransaction()
                                            .replace(R.id.property_content, mMultiPaymentFragment, "listFragment")
                                            .commitAllowingStateLoss()
                                } else {

                                    finishImmediately = true
                                    //只存在一套房产的时候进入详情页面
                                    val myPropertyEntity = fromJson.data[0]
                                    val mPaymentDetailFragment = PaymentDetailFragment.newInstance(myPropertyEntity.id)
                                    supportFragmentManager
                                            .beginTransaction()
                                            .add(R.id.property_content, mPaymentDetailFragment, "detailFragment")
                                            .commitAllowingStateLoss()

                                }
                            }
                        }
                        else -> {
                            showToastShort(fromJson.message)
                        }
                    }
                    else -> {
                        val bundle = Bundle()
                        bundle.putString("type", "add")
                        readyGo(ResidentCertificationActivity::class.java, bundle)
                        tv_top_right.visibility = View.INVISIBLE
                    }

                }
                Log.e(BUG_TAG, json)
            }

            override fun requestFail() {
            }
        })

    }


    private fun initViewAndEvent() {

        tv_page_name.text = "物业缴费"


        iv_share_right.setImageResource(R.drawable.icon_overflow)
        iv_share_right.visibility = View.VISIBLE
        iv_share_right.setOnClickListener(this)
        back_left.setOnClickListener(this)

    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            handleBackKey()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun update(simpleEvent: SimpleEvent) {
        if (simpleEvent.mEventType != SimpleEvent.ADD_PROPERTY) {
            return
        }
        when (simpleEvent.mEventValue) {
            0x0001 -> {
                initEmptyView()
                initViewAndEvent()
                initData()
            }
        }
    }

    override fun onDestroy() {
        EventUtil.getInstance().unregister(this)
        super.onDestroy()
    }
}
